<script setup lang="ts">
  import { postPatientAddAPI ,getPatientInfoByIdAPI,putPatientUpdateAPI} from '@/apis/patient'
import type { PostPatientAddParams } from '@/types/patient'
import type { SwitchOnChangeEvent } from '@uni-helper/uni-app-types'
import { ref } from 'vue'
import { onLoad,onReady } from '@dcloudio/uni-app'

  // 1.收集表单数据
  const formData=ref<PostPatientAddParams>({
    defaultFlag: 0,
    gender: 1,
    idCard: '',
    name: '',
  
  })
  // 2.检验规则
  const formRules=ref<UniHelper.UniFormsRules>({
    name:{
      rules:[
        {required:true,errorMessage:'请填写患者姓名'},
        {pattern:/^(?:[\u4e00-\u9fa5·]{2,16})$/,errorMessage: '患者姓名为2-5位中文'}
      ]
    },
    idCard:{
      rules:[
        {required:true,errorMessage:'请填写患者身份证号'},
        {
        pattern:
          /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
        errorMessage: '请输入正确的身份证号',
      },
      ]
    },
    gender:{
      rules:[
        {required:true,errorMessage:'请选择性别'},
        {
          // 自定义校验规则
          validateFunction:(rule,value,data,callback)=>{
         // 获取身份证号第17位
         const idCardGenderNumber=formData.value.idCard.charAt(16)
         // 判断身份证号第17位是否与选择的性别不一致(取余的方法)
         if(Number(idCardGenderNumber)%2!==value){
          callback('身份证号与性别不匹配')

         }
         return true
          }
        }
      ]
    }

  } ) 

  // 3.表单校验和提交
  const formRef=ref<UniHelper.UniFormsInstance>()
// 保存
const onSubmit=async()=>{
  // 校验表单
  await formRef.value?.validate?.()
  if(props.id){
    const{name,idCard,defaultFlag,id,gender}=formData.value
      // 编辑患者
    await putPatientUpdateAPI({name,idCard,defaultFlag,id,gender})}else{
      // 调用接口，注意：一个帐号最多添加 6 个患者
    await postPatientAddAPI(formData.value)
    }
// #ifdef H5
  // H5端的返回上一页
  window.history.back()
  // #endif

  // #ifdef MP-WEIXIN
  // 跳转回患者列表页，H5端偶尔出现兼容性问题
  uni.navigateBack()
  // #endif
  // 提示保存成功
  uni.showToast({
    title:'保存成功',
    icon:'success'
  })
  
}

  // 4.Switch 开关组件切换事件
  const onChangeDefaultFlag=(event:UniHelper.SwitchOnChangeEvent)=>{
    formData.value.defaultFlag=event.detail.value?1:0
    
  }

  // 5. 接收页面参写法1
onLoad((options) => {
  console.log('页面加载时获取页面参数', options)
})

// 5. 接收页面参写法2-更方便
  const props = defineProps<{ id?: string }>()
console.log('页面级组件，可通过 props 接收页面参数', props)
onReady(()=>{
  // 动态设置导航栏标题
uni.setNavigationBarTitle({ title: props.id ? '编辑患者' : '添加患者' })
})
  const  getPatientInfoById=async()=>{
  // 如果 props.id 存在，则查询患者详情
  if (props.id) {
    //   // 根据患者id获取详情
    const res = await getPatientInfoByIdAPI(props.id)
    console.log('患者详情', res)
      // 保存患者信息，在表单中回显
      formData.value = res.data
  }
}
getPatientInfoById()
  
</script>

<template>
  <scroll-view>
    <view class="archive-page">
      <uni-forms border :model="formData" ref="formRef" :rules="formRules" label-width="220rpx" >
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
          v-model="formData.name"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
          v-model="formData.idCard"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
          v-model="formData.gender"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="defaultFlag">
          <view class="uni-switch">
            <switch
            :checked="formData.defaultFlag===1"
            @change="onChangeDefaultFlag"
             color="#20c6b2"
              style="transform: scale(0.7)" />
          </view>
        </uni-forms-item>
        <button class="uni-button" @tap="onSubmit">保存</button>
      </uni-forms>
      {{ formData }}
    </view>
  </scroll-view>
</template>

<style lang="scss">
  @import './index.scss';
</style>